package com.sdkj.recruit.util;

import java.net.URLEncoder;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import net.sf.json.JSONObject;

public class SinzkUtil {

	private static final Logger logger = Logger.getLogger(SinzkUtil.class);
	public static final String OPEN_ID = "1726008";
	public static final String TOKEN = "jpwmh6rtj1y28edl3y55mpv3o6z1thbn";
	public static final String BASE_URL = "https://api.sinzk.com";
	public static final String SHORT_URL ="7cc3c0a58929912f52334534359536f7";
	private static final char[] HEX_DIGITS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd','e', 'f' };
	
	/**
	 * 文件上传
	 * 
	 * @return
	 */
	public static String convertlist(String openid,String token) {

		String url = BASE_URL + "/upload/convertlist";
		String jsapi_ticket = "openid="+openid+token;
		String sign = MD5Util.string2MD5(jsapi_ticket);
		//System.out.println(sign.toUpperCase());
		JSONObject obj = new JSONObject();
		obj.put("openid", "1726008");
		obj.put("sign", sign.toUpperCase());
		String result = HttpAccessUtil.httpPostBody(url, obj);
		logger.info(result);
		return result;
	}

	
	/**
	 * 文件上传
	 * @param path
	 * @param openid
	 * @return
	 */
	public static String upload(String path,String openid,String token) {

		String url = BASE_URL + "/upload/file";
		String jsapi_ticket = "openid="+openid+token;
		String sign = MD5Util.string2MD5(jsapi_ticket);
		//System.out.println(sign.toUpperCase());
		JSONObject obj = new JSONObject();
		obj.put("openid", openid);
		obj.put("sign", sign.toUpperCase());
		String result = HttpAccessUtil.httpPostBodyFile(url, obj,path);
		logger.info(result);
		return result;
	}

	
	/**
	 * 文件预览
	 * @param openid
	 * @param fid
	 * @return
	 */
	public static String fileview(String openid,String fid,String token) {

		String url = BASE_URL + "/upload/fileview";
		String jsapi_ticket = "fid="+fid+"&openid="+openid+token;
		String sign = MD5Util.string2MD5(jsapi_ticket);
		//System.out.println(sign.toUpperCase());
		JSONObject obj = new JSONObject();
		obj.put("openid", openid);
		obj.put("sign", sign.toUpperCase());
		obj.put("fid", fid);
		String result = HttpAccessUtil.httpPostBody(url, obj);
		logger.info(result);
		return result;
	}
	
	
	/**
	 * 删除文件
	 * @param openid
	 * @param fid
	 * @param token
	 * @return
	 */
	public static String deletefile(String openid,String fid,String token) {

		String url = BASE_URL + "/upload/deletefile";
		String jsapi_ticket = "fid="+fid+"&openid="+openid+token;
		String sign = MD5Util.string2MD5(jsapi_ticket);
		//System.out.println(sign.toUpperCase());
		JSONObject obj = new JSONObject();
		obj.put("openid", openid);
		obj.put("sign", sign.toUpperCase());
		obj.put("fid", fid);
		
		String result = HttpAccessUtil.httpPostBody(url, obj);
		logger.info(result);
		return result;
	}

	
	
	/**
	 * 文件下单
	 * 
	 * @param openid
	 * @param fid
	 * @param token
	 * @return
	 */
	public static String fileorder(String openid,int fid,String token,int number,int pptset,int ptype ,int 
			orientation   ) {

		String url = BASE_URL + "/order/fileorder";
		String jsapi_ticket = "fid="+fid+"&openid="+openid+token;
		String sign = MD5Util.string2MD5(jsapi_ticket);
		//System.out.println(sign.toUpperCase());
		JSONObject obj = new JSONObject();
		obj.put("openid", openid);
		obj.put("sign", sign.toUpperCase());
		obj.put("fid", fid);
		
		String result = HttpAccessUtil.httpPostBody(url, obj);
		logger.info(result);
		return result;
	}
	
	/**
	 * 扫码获取订单列表
	 * 
	 * @param openid
	 * @param token
	 * @param shortStr 二维码短链接
	 * @return
	 */
	public static String scanorder(String openid, String token, String shortStr) {

		String url = BASE_URL + "/order/scanorder";
		String jsapi_ticket = "openid=" + openid + "&short=" + shortStr + token;
		String sign = MD5Util.string2MD5(jsapi_ticket);
		//System.out.println(sign.toUpperCase());
		JSONObject obj = new JSONObject();
		obj.put("openid", openid);
		obj.put("sign", sign.toUpperCase());
		obj.put("short", shortStr);
		String result = HttpAccessUtil.httpPostBody(url, obj);
		logger.info(result);
		return result;
	}
	
	/**
	 * 扫码打印
	 * 
	 * @param openid
	 * @param token
	 * @param shortStr    短连接标识(从机器二维码中获得)
	 * @param ordercode   取件码
	 * @param name        文件名
	 * @param fileUrl     文件地址
	 * @param ptype       单双面(1-单面 2-双面)
	 * @param pptset      多合一(1,2,4,6,9,16)
	 * @param page        文件页数
	 * @param number      打印份数
	 * @param orientation 横竖版(0-竖版(默认) 1-横版)
	 * @return
	 */
	public static String scanprint(String openid, String token, String shortStr, String ordercode, String name,
			String fileUrl, int ptype, int pptset, int page, int number, int orientation) {

		String url = BASE_URL + "/order/scanprint";
		String jsapi_ticket = "openid=" + openid + "&ordercode="+ordercode+"&page="+page+"&short=" + shortStr+"&url="+fileUrl + token;
		String sign = MD5Util.string2MD5(jsapi_ticket);
		//System.out.println(sign.toUpperCase());
		JSONObject obj = new JSONObject();
		obj.put("openid", openid);
		obj.put("sign", sign.toUpperCase());
		obj.put("short", shortStr);
		obj.put("url", fileUrl);
		obj.put("page", page);
		obj.put("ordercode", ordercode);
		String result = HttpAccessUtil.httpPostBody(url, obj);
		logger.info(result);
		return result;
	}
	
	/**
	 * 取消订单
	 * 
	 * @param openid
	 * @param token
	 * @param ordercode
	 * @return
	 */
	public static String cancelorder(String openid, String token, String ordercode) {

		String url = BASE_URL + "/order/cancelorder";
		String jsapi_ticket = "openid=" + openid + "&ordercode" + ordercode + token;
		String sign = MD5Util.string2MD5(jsapi_ticket);
		//System.out.println(sign.toUpperCase());
		JSONObject obj = new JSONObject();
		obj.put("openid", openid);
		obj.put("sign", sign.toUpperCase());
		obj.put("ordercode", ordercode);

		String result = HttpAccessUtil.httpPostBody(url, obj);
		logger.info(result);
		return result;
	}
	
	
	/**
	 * 订单列表
	 * @param openid
	 * @param token
	 * @return
	 */
	public static String orderlist(String openid, String token) {

		String url = BASE_URL + "/order/orderlist";
		String jsapi_ticket = "openid=" + openid+ token;
		String sign = MD5Util.string2MD5(jsapi_ticket);
		//System.out.println(sign.toUpperCase());
		JSONObject obj = new JSONObject();
		obj.put("openid", openid);
		obj.put("sign", sign.toUpperCase());
		String result = HttpAccessUtil.httpPostBody(url, obj);
		logger.info(result);
		return result;
	}
	
	/**
	 * 订单详情
	 * @param openid
	 * @param token
	 * @param fid
	 * @return
	 */
	public static String orderdetail(String openid, String token,String ordercode ) {

		String url = BASE_URL + "/order/orderdetail";
		
		Map<String, String> paraMap =new HashMap<String, String>();
		paraMap.put("openid", openid);
		paraMap.put("ordercode", ordercode);
		String orderUrl =formatUrlMap(paraMap, false, false);
		logger.info(orderUrl);
		String jsapi_ticket = orderUrl+ token;
		String sign = MD5Util.string2MD5(jsapi_ticket);
		//System.out.println(sign.toUpperCase());
		JSONObject obj = new JSONObject();
		obj.put("openid", openid);
		obj.put("ordercode", ordercode);
		obj.put("sign", sign.toUpperCase());
		String result = HttpAccessUtil.httpPostBody(url, obj);
		logger.info(result);
		return result;
	}
	
	/**
	 * 退款订单
	 * 
	 * @param openid
	 * @param token
	 * @param ordernumber
	 * @param re_type
	 * @return
	 */
	public static String orderrefund(String openid, String token, String ordernumber, int re_type) {

		String url = BASE_URL + "/order/orderrefund";
		String jsapi_ticket = "openid=" + openid + token;
		String sign = MD5Util.string2MD5(jsapi_ticket);
		//System.out.println(sign.toUpperCase());
		JSONObject obj = new JSONObject();
		obj.put("openid", openid);
		obj.put("sign", sign.toUpperCase());
		String result = HttpAccessUtil.httpPostBody(url, obj);
		logger.info(result);
		return result;
	}
	
	/**
	 * 云机信息
	 * 
	 * @param openid
	 * @param token
	 * @return
	 */
	public static String getcloudmcstatus(String openid, String token) {

		String url = BASE_URL + "/product/getcloudmcstatus";
		String jsapi_ticket = "openid=" + openid + token;
		String sign = MD5Util.string2MD5(jsapi_ticket);
		System.out.println(sign.toUpperCase());
		JSONObject obj = new JSONObject();
		obj.put("openid", openid);
		obj.put("sign", sign.toUpperCase());
		String result = HttpAccessUtil.httpPostBody(url, obj);
		logger.info(result);
		return result;
	}
	
	/**
	 * 支付宝支付
	 * @param openid
	 * @param token
	 * @param ordernumber
	 * @return
	 */
	public static String mspay(String openid, String token,String ordernumber ) {

		String url = BASE_URL + "/pay/mspay";
		String jsapi_ticket = "openid=" + openid + token;
		String sign = MD5Util.string2MD5(jsapi_ticket);
		//System.out.println(sign.toUpperCase());
		JSONObject obj = new JSONObject();
		obj.put("openid", openid);
		obj.put("sign", sign.toUpperCase());
		String result = HttpAccessUtil.httpPostBody(url, obj);
		logger.info(result);
		return result;
	}
	
	
	  /**
	    *  对所有传入参数按照字段名的Unicode码从小到大排序（字典序），并且生成url参数串<br>
	  * @param paraMap
	  * @param urlEncode
	  * @param keyToLower
	  * @return
	  */
    public static String formatUrlMap(Map<String, String> paraMap, boolean urlEncode, boolean keyToLower)
    {
        String buff = "";
        Map<String, String> tmpMap = paraMap;
        try
        {
            List<Map.Entry<String, String>> infoIds = new ArrayList<Map.Entry<String, String>>(tmpMap.entrySet());
            // 对所有传入参数按照字段名的 ASCII 码从小到大排序（字典序）
            Collections.sort(infoIds, new Comparator<Map.Entry<String, String>>()
            {
 
                @Override
                public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2)
                {
                    return (o1.getKey()).toString().compareTo(o2.getKey());
                }
            });
            // 构造URL 键值对的格式
            StringBuilder buf = new StringBuilder();
            for (Map.Entry<String, String> item : infoIds)
            {
                if (StringUtils.isNotEmptyString(item.getKey()))
                {
                    String key = item.getKey();
                    String val = item.getValue();
                    if (urlEncode)
                    {
                        val = URLEncoder.encode(val, "utf-8");
                    }
                    if (keyToLower)
                    {
                        buf.append(key.toLowerCase() + "=" + val);
                    } else
                    {
                        buf.append(key + "=" + val);
                    }
                    buf.append("&");
                }
 
            }
            buff = buf.toString();
            if (buff.isEmpty() == false)
            {
                buff = buff.substring(0, buff.length() - 1);
            }
        } catch (Exception e)
        {
           return null;
        }
        return buff;
    }

    
	public static void main(String[] args) {
		orderdetail(OPEN_ID, TOKEN, "82837098");
		//scanprint(OPEN_ID, TOKEN, SHORT_URL, "82837098", "test1.pdf", "https:\\/\\/sinzk-new-run-pdf.oss-cn-zhangjiakou.aliyuncs.com\\/201810235bced3f6124e3.pdf?OSSAccessKeyId=LTAI70vyEC7fd9gM&Expires=1540290691&Signature=aqv2iqt6ri7vwTjPrOsbkyv1kjc%3D", 0, 0, 30, 0, 0);
		//getcloudmcstatus("1726008", "jpwmh6rtj1y28edl3y55mpv3o6z1thbn");
		//orderlist("1726008", "jpwmh6rtj1y28edl3y55mpv3o6z1thbn");
		//scanorder("1726008", "jpwmh6rtj1y28edl3y55mpv3o6z1thbn", SHORT_URL);
		//fileorder("1726008", 1968190, "jpwmh6rtj1y28edl3y55mpv3o6z1thbn", 1, 0, 0, 0);
		//fileview("1726008", "1968190","jpwmh6rtj1y28edl3y55mpv3o6z1thbn");
		//convertlist();
		//upload("D:\\test1.pdf","1726008");
	}

	public static String encode(String str) {
		if (str == null) {
			return null;
		}
		try {
			MessageDigest messageDigest = MessageDigest.getInstance("SHA1");
			messageDigest.update(str.getBytes());
			return getFormattedText(messageDigest.digest());
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	private static String getFormattedText(byte[] bytes) {
		int len = bytes.length;
		StringBuilder buf = new StringBuilder(len * 2);
		// 把密文转换成十六进制的字符串形式
		for (int j = 0; j < len; j++) {
			buf.append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f]);
			buf.append(HEX_DIGITS[bytes[j] & 0x0f]);
		}
		return buf.toString();
	}
}
